package cn.iocoder.yudao.module.jifenyuan.service.room;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.jifenyuan.api.wallet.WalletApi;
import cn.iocoder.yudao.module.jifenyuan.api.wallet.dto.WalletRespDto;
import cn.iocoder.yudao.module.jifenyuan.controller.admin.roomuserbind.vo.RoomUserBindBaseVO;
import cn.iocoder.yudao.module.jifenyuan.controller.admin.roomuserbind.vo.RoomUserBindRespVO;
import cn.iocoder.yudao.module.jifenyuan.convert.roomuserbind.RoomUserBindConvert;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.room.RoomWithBindTypeDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.roomlog.RoomLogDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.roomlog.RoomLogWithInfoDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.roomuserbind.RoomUserBindDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.roomuserbind.RoomUserBindWithInfoDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.sharecode.ShareCodeDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.usercurrentroom.UserCurrentRoomDO;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.wallet.WalletDO;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.roomlog.RoomLogMapper;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.roomuserbind.RoomUserBindMapper;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.sharecode.ShareCodeMapper;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.usercurrentroom.UserCurrentRoomMapper;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.wallet.WalletMapper;
import cn.iocoder.yudao.module.jifenyuan.enums.*;
import cn.iocoder.yudao.module.jifenyuan.service.notify.NotifyService;
import cn.iocoder.yudao.module.jifenyuan.service.sharecode.ShareCodeService;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.member.api.user.vo.PushMsgVo;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.jifenyuan.controller.app.room.vo.*;
import cn.iocoder.yudao.module.jifenyuan.dal.dataobject.room.RoomDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.jifenyuan.convert.room.RoomConvert;
import cn.iocoder.yudao.module.jifenyuan.dal.mysql.room.RoomMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.jifenyuan.enums.ErrorCodeConstants.*;

/**
 * 记分员 房间 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class RoomServiceImpl implements RoomService {

    @Resource
    private RoomMapper roomMapper;
    @Resource
    private WalletApi walletApi;
    @Value("${jifenyuan.room.create-coin}")
    private Long roomCreateCoin;
    @Value("${jifenyuan.room.join-coin}")
    private Long roomJoinCoin;
    @Value("${jifenyuan.trial-vip}")
    private boolean trialVip;
    @Resource
    private FileApi fileApi;
    @Resource
    private RoomUserBindMapper roomUserBindMapper;
    @Resource
    private UserCurrentRoomMapper currentRoomMapper;
    @Resource
    private WxMaService wxMaService;
    @Resource
    private RoomLogMapper roomLogMapper;
    @Resource
    private MemberUserApi memberUserApi;
    @Resource
    private NotifyService notifyService;
    @Resource
    private ShareCodeMapper shareCodeMapper;
    @Resource
    private WalletMapper walletMapper;


    @Override
    public RoomDO selectCurrentLeaderRoom(){
        RoomDO liveRoom = getLiveRoomByLeaderId(SecurityFrameworkUtils.getLoginUserId());
        return liveRoom;
    }
    @Override
    @DSTransactional
    public RoomDO createRoom(AppRoomCreateReqVO createReqVO) {
        //判断之前是否创建房间
        RoomDO liveRoom = getLiveRoomByLeaderId(SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(liveRoom)) {
            throw exception(ROOM_ALREADY_CREATE);
        }

        //判断是否已经加入其他房间
        UserCurrentRoomDO isJoin = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());

        if (!Objects.isNull(isJoin)) {
            throw exception(ROOM_ALREADY_JOIN);
        }
        //添加房间默认属性
        WalletRespDto walletByUserId = walletApi.getWalletByUserId(SecurityFrameworkUtils.getLoginUserId());

        String inviteCode = IdUtil.fastSimpleUUID();
        String observerCode = IdUtil.fastSimpleUUID();
        createReqVO.setLeaderId(SecurityFrameworkUtils.getLoginUserId());
        createReqVO.setStatus(JifenyuanRoomStatusEnum.ENABLE.getStatus());
        createReqVO.setInviteCode(inviteCode);
        createReqVO.setObserverCode(observerCode);
        createReqVO.setVip(walletByUserId.getVip());
        // 插入
        RoomDO room = RoomConvert.INSTANCE.convert(createReqVO);
        if (!walletByUserId.getVip()) {
            walletApi.changeWallerCoin(SecurityFrameworkUtils.getLoginUserId(), roomCreateCoin, JifenyuanWalletLogChangeTypeEnum.REDUCE.getStatus(), JifenyuanWalletEventTypeEnum.CREATE_ROOM.getName());
            List<String> cids = memberUserApi.getCidsByUserIds(CollectionUtil.newArrayList(SecurityFrameworkUtils.getLoginUserId()));
            if (cids != null && cids.size() > 0) {
                notifyUserCoinChange(cids, roomCreateCoin, JifenyuanRoomEventTypeEnum.COIN_CHANGE, JifenyuanWalletLogChangeTypeEnum.REDUCE);
            }
        }
        roomMapper.insert(room);


        JSONObject payload = new JSONObject();
        payload.set("type", room.getType()); //房间类型
        payload.set("mode", JifenyuanRoomUserTypeEnum.PARTNER.getStatus());//参与者
        payload.set("room", room);//房间
        MemberUserRespDTO user = memberUserApi.getUser(SecurityFrameworkUtils.getLoginUserId());
        payload.set("avatar", user.getAvatar());

        //添加邀请码对应的参数
        ShareCodeDO inviteCodeShare = new ShareCodeDO();
        inviteCodeShare.setShareCode(inviteCode);
        inviteCodeShare.setPayload(payload.toString());
        shareCodeMapper.insert(inviteCodeShare);

        //添加观察码对应的参数
        payload.set("mode", JifenyuanRoomUserTypeEnum.OBSERVER.getStatus());//参与者
        ShareCodeDO observerCodeShare = new ShareCodeDO();
        observerCodeShare.setShareCode(observerCode);
        observerCodeShare.setPayload(payload.toString());
        shareCodeMapper.insert(observerCodeShare);
        //添加房间内人员
        RoomUserBindDO roomUserBindDO = new RoomUserBindDO()
                .setRoomId(room.getId())
                .setUserId(SecurityFrameworkUtils.getLoginUserId())
                .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
                .setScore(0L)
                .setType(JifenyuanRoomUserTypeEnum.PARTNER.getStatus());

        roomUserBindMapper.insert(roomUserBindDO);
        //添加当前人员与房间绑定表
        UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
        userCurrentRoomDO.setRoomId(room.getId());
        userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
        currentRoomMapper.insert(userCurrentRoomDO);
        // 返回
        return room;
    }

    @Override
    public void updateRoom(AppRoomUpdateReqVO updateReqVO) {
        // 校验存在
        validateRoomExists(updateReqVO.getId());
        // 更新
        RoomDO updateObj = RoomConvert.INSTANCE.convert(updateReqVO);
        roomMapper.updateById(updateObj);
    }

    @Override
    public void deleteRoom(Long id) {
        // 校验存在
        validateRoomExists(id);
        // 删除
        roomMapper.deleteById(id);
    }

    private void validateRoomExists(Long id) {
        if (roomMapper.selectById(id) == null) {
            throw exception(ROOM_NOT_EXISTS);
        }
    }

    @Override
    public RoomDO getRoom(Long id) {
        return roomMapper.selectById(id);
    }

    @Override
    public List<RoomDO> getRoomList(Collection<Long> ids) {
        return roomMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<RoomDO> getRoomPage(AppRoomPageReqVO pageReqVO) {
        return roomMapper.selectPage(pageReqVO);
    }

    @Override
    public List<RoomDO> getRoomList(AppRoomExportReqVO exportReqVO) {
        return roomMapper.selectList(exportReqVO);
    }

    @Override
    public RoomDO getLiveRoomByLeaderId(Long userId) {
        return roomMapper.getLiveRoomByLeaderId(userId);
    }

    /**
     * 检查自己是否在房间内，如果是电脑端的观察员在线的话，那就让他用手机重新加入，然后退出，因为退出房间会退出
     * 所有的角色绑定
     *
     * @return
     */
    @Override
    public RoomWithBindTypeDO checkInRoom() {
        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (Objects.isNull(userCurrentRoomDO)) {
            return null;
        } else {
            RoomDO roomDO = roomMapper.selectOne(RoomDO::getId, userCurrentRoomDO.getRoomId());
            RoomWithBindTypeDO roomWithBindTypeDO = RoomConvert.INSTANCE.convert3(roomDO);
            List<RoomUserBindDO> observerUserBindDOs = roomUserBindMapper.selectRoomObserverByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
            if (observerUserBindDOs != null && observerUserBindDOs.size() > 0) {
                roomWithBindTypeDO.setBindType(JifenyuanRoomUserTypeEnum.OBSERVER.getStatus());
            }
            //参与者优先级比较高，覆盖掉参与者
            RoomUserBindDO partnerUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
            if (!Objects.isNull(partnerUserBindDO)) {
                roomWithBindTypeDO.setBindType(partnerUserBindDO.getType());
            }
            MemberUserRespDTO user = memberUserApi.getUser(roomDO.getLeaderId());

            if(!Objects.isNull(user)){
                roomWithBindTypeDO.setLeaderAvatar(user.getAvatar());
            }

            return roomWithBindTypeDO;
        }

    }

    @Override
    public void roomTransfer(Long toUserId, Long score) {
//        RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectById(roomUserBindId);
        //需要判断一下转账双方是不是参与者

        if (SecurityFrameworkUtils.getLoginUserId().equals(toUserId)) {
            throw exception(ROOM_TRANSFER_NOT_SELF);
        }
        UserCurrentRoomDO currentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        RoomUserBindDO fromUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(currentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId());
        if (Objects.isNull(fromUserBindDO)) {
            throw exception(ROOM_USER_BIND_NOT_EXISTS);
        }
        RoomUserBindDO toUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(currentRoomDO.getRoomId(), toUserId);
        if (Objects.isNull(toUserBindDO)) {
            throw exception(ROOM_USER_BIND_NOT_EXISTS);
        }
        roomUserBindMapper.addScore(currentRoomDO.getRoomId(), toUserId, score);
        roomUserBindMapper.reduceScore(currentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId(), score);
        RoomLogDO roomLogDO = new RoomLogDO();
        roomLogDO.setRoomId(currentRoomDO.getRoomId()).setFromUser(SecurityFrameworkUtils.getLoginUserId()).setToUser(toUserId).setScore(score);

        roomLogMapper.insert(roomLogDO);
        notifyPartner(currentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId(), toUserId, score, JifenyuanRoomEventTypeEnum.SCORE_CHANGE);
        notifyObserver(currentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId(), toUserId, score, JifenyuanRoomEventTypeEnum.SCORE_CHANGE);
    }

    public void notifyPartner(Long roomId, Long fromUserId, Long toUserId, Long score, JifenyuanRoomEventTypeEnum type) {
        List<RoomUserBindDO> roomUserBindDOS = roomUserBindMapper.selectRoomOnlinePartnerList(roomId);

        List<Long> userIds = roomUserBindDOS.stream().map(ele -> ele.getUserId()).collect(Collectors.toList());
        notifyService.notifyPartner(userIds, fromUserId, toUserId, score, type);

    }

    public void notifyObserver(Long roomId, Long fromUserId, Long toUserId, Long score, JifenyuanRoomEventTypeEnum type) {
        List<RoomUserBindDO> roomUserBindDOS = roomUserBindMapper.selectRoomOnlineObserverList(roomId);

        List<String> mpcids = roomUserBindDOS.stream().filter(ele -> JifenyuanObserverSourceEnum.mp.getStatus().equals(ele.getObserverSource())).map(ele -> ele.getCid()).collect(Collectors.toList());
        List<String> webcids = roomUserBindDOS.stream().filter(ele -> JifenyuanObserverSourceEnum.WEB.getStatus().equals(ele.getObserverSource())).map(ele -> ele.getCid()).collect(Collectors.toList());
        if (mpcids != null && mpcids.size() > 0) {
            notifyService.notifyObserver(mpcids, fromUserId, toUserId, score, type);
        }
        if (webcids != null && webcids.size() > 0) {
            notifyService.notifyWebObserver(webcids, fromUserId, toUserId, score, type);

        }

    }

    public void notifyUserCoinChange(List<String> cids, Long score, JifenyuanRoomEventTypeEnum type, JifenyuanWalletLogChangeTypeEnum coinChangeType) {

        notifyService.notifyCoinChange(cids, score, type, coinChangeType);
    }

    @Override
    public List<RoomUserBindDO> getRoomScore() {
        UserCurrentRoomDO currentRoom = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (Objects.isNull(currentRoom)) {
            throw exception(ROOM_NO_PARTNER);
        }
        //获取房间内参与者
        List<RoomUserBindDO> roomUserBindDOs = roomUserBindMapper.selectRoomPartnerList(currentRoom.getRoomId());
        return roomUserBindDOs;
    }

    @Override
    public List<RoomUserBindWithInfoDO> getRoomPartner() {
        UserCurrentRoomDO currentRoom = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (Objects.isNull(currentRoom)) {
            throw exception(ROOM_NO_PARTNER);
        }
        //获取房间内参与者
        List<RoomUserBindDO> roomUserBindDOs = roomUserBindMapper.selectRoomPartnerList(currentRoom.getRoomId());
        if (roomUserBindDOs != null && roomUserBindDOs.size() > 0) {
            List<RoomUserBindWithInfoDO> roomUserBindWithInfoDOS = RoomUserBindConvert.INSTANCE.convertList03(roomUserBindDOs);
            HashSet<Long> userIds = new HashSet<>();
            for (RoomUserBindWithInfoDO roomUserBindWithInfoDO : roomUserBindWithInfoDOS) {
                userIds.add(roomUserBindWithInfoDO.getUserId());
            }
            List<Long> userIdList = new ArrayList<>();
            userIdList.addAll(userIds);
            List<MemberUserRespDTO> users = memberUserApi.getUsers(userIdList);
            for (RoomUserBindWithInfoDO roomUserBindWithInfoDO : roomUserBindWithInfoDOS) {
                MemberUserRespDTO fromUserRespDTO = users.stream().filter(i -> i.getId().equals(roomUserBindWithInfoDO.getUserId())).findFirst().orElse(null);
                if (fromUserRespDTO != null) {
                    roomUserBindWithInfoDO.setNickname(fromUserRespDTO.getNickname());
                    roomUserBindWithInfoDO.setAvatar(fromUserRespDTO.getAvatar());
                }

            }
            return roomUserBindWithInfoDOS;
        }

        return null;


    }

    /**
     * 因为加入观察员可能会有参与者（电脑端），所以要考虑一下,如果时同一个用户 观察员与参与者是两条记录,
     * 必须登录
     * <p>
     * if(是否有当前房间){
     * if(是否与要加入的房间是一个){
     * if(按照source判断是否已经加入过){
     * if（离线了）{
     * 更新为在线
     * 返回房间
     * }else{
     * 返回房间
     * }
     * }else{
     * 按照source加入观察者
     * 返回房间
     * }
     * }else{
     * 不管是观察者还是参与者
     * 报错，要求先退出当前的房间
     * }
     * }else{
     * 添加现在房间
     * if（是否有之前的绑定关系）{
     * *              上线
     * *
     * *              }else{
     * *                  添加绑定关系
     * if(不是会员){
     * 添加扣费
     * 发送扣费通知
     * }
     * }
     * <p>
     * <p>
     * 返回房间
     * }
     *
     * @param observerCode
     * @return
     */
    @Override
    public RoomDO joinObserverRoom(String observerCode, String cid, String observerSource) {

        UserCurrentRoomDO currentRoom = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        RoomDO roomDO = roomMapper.selectOnlineRoomByObserverCode(observerCode);
        if (Objects.isNull(roomDO)) {
            throw exception(ROOM_NOT_EXISTS);
        }
        if (!Objects.isNull(currentRoom)) {
            if (currentRoom.getRoomId().equals(roomDO.getId())) {
                RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomObserverByUserIdAndSource(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId(), observerSource);
                if (!Objects.isNull(roomUserBindDO)) {
                    if (roomUserBindDO.getStatus().equals(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus())) {
                        roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());
                        roomUserBindDO.setCid(cid);
                        roomUserBindMapper.updateById(roomUserBindDO);
                        return roomDO;
                    } else {
                        roomUserBindDO.setCid(cid);
                        roomUserBindMapper.updateById(roomUserBindDO);
                        return roomDO;
                    }
                } else {
                    //添加观察员绑定g
                    RoomUserBindDO joinDo = new RoomUserBindDO()
                            .setRoomId(roomDO.getId())
                            .setUserId(SecurityFrameworkUtils.getLoginUserId())
                            .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
                            .setScore(0L)
                            .setObserverSource(observerSource)
                            .setType(JifenyuanRoomUserTypeEnum.OBSERVER.getStatus())
                            .setCid(cid);

                    roomUserBindMapper.insert(joinDo);
                    return roomDO;
                }

            } else {
                throw exception(ROOM_ALREADY_JOIN);
            }
        } else {
            UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
            userCurrentRoomDO.setRoomId(roomDO.getId());
            userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
            currentRoomMapper.insert(userCurrentRoomDO);

            RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomObserverByUserIdAndSource(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId(), observerSource);

            if (Objects.isNull(roomUserBindDO)) {
                //添加观察员绑定g
                RoomUserBindDO joinDo = new RoomUserBindDO()
                        .setRoomId(roomDO.getId())
                        .setUserId(SecurityFrameworkUtils.getLoginUserId())
                        .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
                        .setScore(0L)
                        .setObserverSource(observerSource)
                        .setType(JifenyuanRoomUserTypeEnum.OBSERVER.getStatus())
                        .setCid(cid);

                roomUserBindMapper.insert(joinDo);

                //扣费
                WalletDO walletDO = walletMapper.selectWalletByUserId(SecurityFrameworkUtils.getLoginUserId());
                if(!walletDO.getVip()){
                    walletApi.changeWallerCoin(SecurityFrameworkUtils.getLoginUserId(), roomJoinCoin, JifenyuanWalletLogChangeTypeEnum.REDUCE.getStatus(), JifenyuanWalletEventTypeEnum.JOIN_ROOM.getName());
                    List<String> cids = memberUserApi.getCidsByUserIds(CollectionUtil.newArrayList(SecurityFrameworkUtils.getLoginUserId()));
                    if (cids != null && cids.size() > 0) {
                        notifyUserCoinChange(cids, roomJoinCoin, JifenyuanRoomEventTypeEnum.COIN_CHANGE, JifenyuanWalletLogChangeTypeEnum.REDUCE);
                    }
                }

            } else {
                //有绑定关系 直接加入
                roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());

                roomUserBindMapper.updateById(roomUserBindDO);
            }


            return roomDO;
        }


//        //先判断之前加入过没有，如果有 直接加入 如果没有 扣除金币
//
//        if (Objects.isNull(roomDO)) {
//            throw exception(ROOM_NOT_EXISTS);
//        }
//        RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomObserverByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
//        if (Objects.isNull(roomUserBindDO)) {
//            //如果观察者是房间内的partner时，不重复扣款
//            RoomUserBindDO partner = roomUserBindMapper.selectRoomPartnerByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
//            if (Objects.isNull(partner)) {
//                walletApi.changeWallerCoin(SecurityFrameworkUtils.getLoginUserId(), roomJoinCoin, JifenyuanWalletLogChangeTypeEnum.REDUCE.getStatus(), JifenyuanWalletEventTypeEnum.JOIN_ROOM.getName());
//                List<String> cids = memberUserApi.getCidsByUserIds(CollectionUtil.newArrayList(SecurityFrameworkUtils.getLoginUserId()));
//                if (cids!=null && cids.size()>0){
//                    notifyUserCoinChange(cids,roomJoinCoin,JifenyuanRoomEventTypeEnum.COIN_CHANGE,JifenyuanWalletLogChangeTypeEnum.REDUCE);
//                }
//            }else{
//                //添加观察员绑定g
//                RoomUserBindDO joinDo = new RoomUserBindDO()
//                        .setRoomId(roomDO.getId())
//                        .setUserId(SecurityFrameworkUtils.getLoginUserId())
//                        .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
//                        .setScore(0L)
//                        .setObserverSource(observerSource)
//                        .setType(JifenyuanRoomUserTypeEnum.OBSERVER.getStatus())
//                        .setCid(cid);
//
//                roomUserBindMapper.insert(joinDo);
//                if(StringUtils.equals(observerCode,JifenyuanObserverSourceEnum.mp.getStatus())){
//                    //小程序这一端需要绑定当前房间，
//                    //添加当前人员与房间绑定表
//                    UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
//                    userCurrentRoomDO.setRoomId(roomDO.getId());
//                    userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
//                    currentRoomMapper.insert(userCurrentRoomDO);
//                }
//
//            }
//        }else{
//            roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());
//            roomUserBindMapper.updateById(roomUserBindDO);
//            //添加当前人员与房间绑定表
//            UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
//            userCurrentRoomDO.setRoomId(roomDO.getId());
//            userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
//            currentRoomMapper.insert(userCurrentRoomDO);
//        }
//        return roomDO;
    }

    /**
     * 参与者身份加入房间
     * <p>
     * if(是否有当前房间){
     * if(是否与要加入的房间是一个){
     * if(绑定关系是否是参与者){
     * if（是否离线）{
     * 更新为在线
     * 发送所有推送
     * <p>
     * 返回房间
     * }else{
     * 返回房间
     * }
     * }else{
     * 添加参与者绑定关系
     * 发送推送
     * }
     * }else{
     * 报错，要求退出当前房间
     * }
     * }else{
     * 添加现在房间，
     * if（是否有之前的绑定关系）{
     * 上线
     * <p>
     * }else{
     * 添加绑定关系
     * if(不是会员){
     * 添加扣费
     * 发送扣费推送
     * }

     * }
     * <p>
     * 发送成员推送
     * <p>
     * <p>
     * 返回房间
     * }
     *
     * @param inviteCode
     * @return
     */
    @Override
    public RoomDO joinPartnerRoom(String inviteCode) {
        RoomDO roomDO = roomMapper.selectOnlineRoomByShareCode(inviteCode);
        if (Objects.isNull(roomDO)) {
            throw exception(ROOM_NOT_EXISTS);
        }
        if(trialVip){
            WalletDO walletDO = walletMapper.selectOne(WalletDO::getUserId, roomDO.getLeaderId());
            if(walletDO.getVip()){
                //已经是vip了 不操作
            }else{
                walletMapper.addWalletVip(roomDO.getLeaderId(),30);
            }

        }
        UserCurrentRoomDO currentRoom = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(currentRoom)) {
            if (currentRoom.getRoomId().equals(roomDO.getId())) {
                RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
                if (!Objects.isNull(roomUserBindDO)) {
                    if (roomUserBindDO.getStatus().equals(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus())) {
                        roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());
                        roomUserBindMapper.updateById(roomUserBindDO);
                        notifyPartner(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
                        notifyObserver(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
                        return roomDO;
                    } else {
                        return roomDO;
                    }
                } else {
                    RoomUserBindDO joinDo = new RoomUserBindDO()
                            .setRoomId(roomDO.getId())
                            .setUserId(SecurityFrameworkUtils.getLoginUserId())
                            .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
                            .setScore(0L)
                            .setType(JifenyuanRoomUserTypeEnum.PARTNER.getStatus());

                    roomUserBindMapper.insert(joinDo);
                    notifyPartner(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
                    notifyObserver(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
                    return roomDO;
                }
            } else {
                throw exception(ROOM_ALREADY_JOIN);
            }
        } else {
            //添加当前人员与房间绑定表
            UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
            userCurrentRoomDO.setRoomId(roomDO.getId());
            userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
            currentRoomMapper.insert(userCurrentRoomDO);

            RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());

            if (Objects.isNull(roomUserBindDO)) {
                RoomUserBindDO joinDo = new RoomUserBindDO()
                        .setRoomId(roomDO.getId())
                        .setUserId(SecurityFrameworkUtils.getLoginUserId())
                        .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
                        .setScore(0L)
                        .setType(JifenyuanRoomUserTypeEnum.PARTNER.getStatus());

                roomUserBindMapper.insert(joinDo);
                if (!roomDO.getVip()) {
                    WalletDO walletDO = walletMapper.selectWalletByUserId(SecurityFrameworkUtils.getLoginUserId());
                    if(!walletDO.getVip()){
                        walletApi.changeWallerCoin(SecurityFrameworkUtils.getLoginUserId(), roomJoinCoin, JifenyuanWalletLogChangeTypeEnum.REDUCE.getStatus(), JifenyuanWalletEventTypeEnum.JOIN_ROOM.getName());
                        List<String> cids = memberUserApi.getCidsByUserIds(CollectionUtil.newArrayList(SecurityFrameworkUtils.getLoginUserId()));
                        if (cids != null && cids.size() > 0) {
                            notifyUserCoinChange(cids, roomJoinCoin, JifenyuanRoomEventTypeEnum.COIN_CHANGE, JifenyuanWalletLogChangeTypeEnum.REDUCE);
                        }
                    }


                }
            } else {
                //有绑定关系 直接加入
                roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());

                roomUserBindMapper.updateById(roomUserBindDO);
            }

            notifyPartner(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
            notifyObserver(roomDO.getId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);

            return roomDO;
        }


////要判断一下要加入的房间是否是当前绑定的房间 ，如果不是，则需要把当前的房间给解绑掉
//        if(currentRoom!=null){
//            if(currentRoom.getRoomId().equals(roomDO.getId())){
//                //是一个房间
//                return roomDO;
//            }else{
//                //不是一个房间
//                leaveCurrentRoom();
//
//            }
//        }
//        RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(roomDO.getId(), SecurityFrameworkUtils.getLoginUserId());
//        if (Objects.isNull(roomUserBindDO)) {
//            //没有绑定关系，判断是否是vip房间 如果不是扣费加入
//            if (!roomDO.getVip()) {
//                walletApi.changeWallerCoin(SecurityFrameworkUtils.getLoginUserId(), roomJoinCoin, JifenyuanWalletLogChangeTypeEnum.REDUCE.getStatus(), JifenyuanWalletEventTypeEnum.JOIN_ROOM.getName());
//                List<String> cids = memberUserApi.getCidsByUserIds(CollectionUtil.newArrayList(SecurityFrameworkUtils.getLoginUserId()));
//                if (cids!=null && cids.size()>0){
//                    notifyUserCoinChange(cids,roomJoinCoin,JifenyuanRoomEventTypeEnum.COIN_CHANGE,JifenyuanWalletLogChangeTypeEnum.REDUCE);
//                }
//
//            }
//
//            RoomUserBindDO joinDo = new RoomUserBindDO()
//                    .setRoomId(roomDO.getId())
//                    .setUserId(SecurityFrameworkUtils.getLoginUserId())
//                    .setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
//                    .setScore(0L)
//                    .setType(JifenyuanRoomUserTypeEnum.PARTNER.getStatus());
//
//            roomUserBindMapper.insert(joinDo);
//
//            //添加当前人员与房间绑定表
//            UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
//            userCurrentRoomDO.setRoomId(roomDO.getId());
//            userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
//            currentRoomMapper.insert(userCurrentRoomDO);
//        } else {
//
//            //有绑定关系 直接加入
//            roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.ONLINE.getStatus());
//
//            roomUserBindMapper.updateById(roomUserBindDO);
//            //添加当前人员与房间绑定表
//            UserCurrentRoomDO userCurrentRoomDO = new UserCurrentRoomDO();
//            userCurrentRoomDO.setRoomId(roomDO.getId());
//            userCurrentRoomDO.setUserId(SecurityFrameworkUtils.getLoginUserId());
//            currentRoomMapper.insert(userCurrentRoomDO);
//        }
//
//        notifyPartner(roomDO.getId(),null,null,null,JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
//        notifyObserver(roomDO.getId(),null,null,null,JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
//
//
//        return roomDO;
//

    }

    @Override
    public String getRoomObserveImg() {
        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(userCurrentRoomDO)) {
            RoomDO roomDO = roomMapper.selectOne(RoomDO::getId, userCurrentRoomDO.getRoomId());
            if (!Objects.isNull(roomDO)) {
                if (StringUtils.isEmpty(roomDO.getObserverCodeUrl())) {
                    try {
                        String s = generateWxCode(roomDO.getObserverCode());
                        RoomDO updatDo = new RoomDO();
                        updatDo.setId(roomDO.getId());
                        updatDo.setObserverCodeUrl(s);
                        roomMapper.updateById(updatDo);
                        return s;
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                } else {
                    return roomDO.getObserverCodeUrl();
                }


            }
        }
        throw exception(USER_GENERATE_INVITE_CODE_FAIL);

    }

    @Override
    public String getRoomShareImg() {
        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(userCurrentRoomDO)) {
            RoomDO roomDO = roomMapper.selectOne(RoomDO::getId, userCurrentRoomDO.getRoomId());
            if (!Objects.isNull(roomDO)) {

                if (StringUtils.isEmpty(roomDO.getInviteCodeUrl())) {
                    try {
                        String s = generateWxCode(roomDO.getInviteCode());
                        RoomDO updatDo = new RoomDO();
                        updatDo.setId(roomDO.getId());
                        updatDo.setInviteCodeUrl(s);
                        roomMapper.updateById(updatDo);
                        return s;
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                } else {
                    return roomDO.getInviteCodeUrl();
                }


            }
        }
        throw exception(USER_GENERATE_INVITE_CODE_FAIL);

    }

    /**
     * 解散房间
     */
    @Override
    public void closeRoom() {
        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(userCurrentRoomDO)) {
            RoomDO roomDO = roomMapper.selectOne(RoomDO::getId, userCurrentRoomDO.getRoomId());
            if (!Objects.isNull(roomDO)) {
                if (SecurityFrameworkUtils.getLoginUserId().equals(roomDO.getLeaderId())) {
                    //房间下线
                    roomDO.setStatus(JifenyuanRoomStatusEnum.DISABLE.getStatus());
                    roomMapper.updateById(roomDO);
                    //绑定关系下线
                    List<RoomUserBindDO> roomUserBindDOS = roomUserBindMapper.selectRoomJoiner(roomDO.getId());
                    List<Long> userIds = new ArrayList<>();
                    List<String> webcids = new ArrayList<>();
                    List<String> mpcids = new ArrayList<>();
                    for (RoomUserBindDO roomUserBindDO : roomUserBindDOS) {
                        if (JifenyuanRoomUserStatusEnum.ONLINE.getStatus().equals(roomUserBindDO.getStatus())) {
                            //如果在线
                            roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus());
                        }
                        if (JifenyuanRoomUserTypeEnum.PARTNER.getStatus().equals(roomUserBindDO.getType())) {
                            userIds.add(roomUserBindDO.getUserId());
                        } else if (JifenyuanRoomUserTypeEnum.OBSERVER.getStatus().equals(roomUserBindDO.getType())) {
                            if (StringUtils.equals(JifenyuanObserverSourceEnum.mp.getStatus(), roomUserBindDO.getObserverSource())) {
                                mpcids.add(roomUserBindDO.getCid());
                            } else {
                                webcids.add(roomUserBindDO.getCid());
                            }

                        }
                    }
                    roomUserBindMapper.updateBatch(roomUserBindDOS);

                    //加入人绑定当前房间下线

                    currentRoomMapper.delete(new LambdaQueryWrapper<UserCurrentRoomDO>().eq(UserCurrentRoomDO::getRoomId, roomDO.getId()));
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.set("type", JifenyuanRoomEventTypeEnum.ROOM_CLOSE.getStatus());
                    jsonObject.set("roomId", userCurrentRoomDO.getRoomId());
//                    发送通知
                    if (userIds.size() > 0) {
                        notifyService.notify(userIds, jsonObject.toString());
                    }
                    if (mpcids.size() > 0) {
                        notifyService.notifyCids(mpcids, jsonObject.toString());
                    }
                    if (webcids.size() > 0) {
                        notifyService.notifyWebCids(webcids, jsonObject.toString());
                    }
                }
            }
        }


    }

    @Override
    public void hideSelf() {

        UserCurrentRoomDO currentRoom = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(currentRoom)) {
            RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(currentRoom.getRoomId(), SecurityFrameworkUtils.getLoginUserId());
            if(!Objects.isNull(roomUserBindDO)){

                roomUserBindMapper.updateRoomPartnerHideByUserId(currentRoom.getRoomId(), SecurityFrameworkUtils.getLoginUserId(),!roomUserBindDO.isHide());
                notifyObserver(currentRoom.getRoomId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);

            }



        }
    }

    private String generateWxCode(String code) throws WxErrorException {
        /**
         * 接口B: 获取小程序码（永久有效、数量暂无限制）.
         * <pre>
         * 通过该接口生成的小程序码，永久有效，数量暂无限制。
         * 用户扫描该码进入小程序后，将统一打开首页，开发者需在对应页面根据获取的码中 scene 字段的值，再做处理逻辑。
         * 使用如下代码可以获取到二维码中的 scene 字段的值。
         * 调试阶段可以使用开发工具的条件编译自定义参数 scene=xxxx 进行模拟，开发工具模拟时的 scene 的参数值需要进行 urlencode
         * </pre>
         *
         * @param scene      最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，
         *                   其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
         * @param page       必须是已经发布的小程序页面，例如 "pages/index/index" ,如果不填写这个字段，默认跳主页面
         * @param checkPath  默认true 检查 page 是否存在，为 true 时 page 必须是已经发布的小程序存在的页面（否则报错）；
         *                   为 false 时允许小程序未发布或者 page 不存在，但 page 有数量上限（60000个）请勿滥用
         * @param envVersion 默认"release" 要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"
         * @param width      默认430 二维码的宽度
         * @param autoColor  默认true 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
         * @param lineColor  autoColor 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"}
         * @param isHyaline  是否需要透明底色， is_hyaline 为true时，生成透明底色的小程序码
         * @return 文件内容字节数组
         * @throws WxErrorException 异常
         * byte[] createWxaCodeUnlimitBytes(String scene, String page, boolean checkPath, String envVersion, int width, boolean autoColor,
         *                 WxMaCodeLineColor lineColor, boolean isHyaline) throws WxErrorException;
         */

        WxMaCodeLineColor color = new WxMaCodeLineColor("64", "108", "231");
        byte[] wxaCodeUnlimitBytes = wxMaService.getQrcodeService()
                .createWxaCodeUnlimitBytes(code, "pages/route/route", false, "release", 120, false, color, true);
        String avatar = fileApi.createFile(wxaCodeUnlimitBytes);
        return  avatar;
//        String encode = Base64.encode(wxaCodeUnlimitBytes);
//        encode = encode.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
//        return "data:image/png;base64," + encode;

    }


    /**
     * 成员离开房间
     * <p>
     * if(是否有当前房间){
     * 获取房间内所有的绑定关系
     * 遍历：
     * if(绑定关系为参与者){
     * 将参与者下线
     * 发送成员推送
     * <p>
     * }else{
     * 将观察者下线
     * }
     * 遍历结束
     * <p>
     * 取消绑定的当前房间
     * 发送推送给这个用户，因为有可能多端同时登录，所以推送要加上房间名，让用户判断一下 如果在当前房间 就退出去
     * if(房间内没有其他在线参与者){
     * 将房间关闭
     * 推送观察者退出
     * }else{
     * 不操作
     * }
     * }else{
     * 不操作
     * }
     */
    @Override
    public void leaveCurrentRoom() {

        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
        if (!Objects.isNull(userCurrentRoomDO)) {
            List<RoomUserBindDO> roomUserBindDOs = roomUserBindMapper.selectRoomJoinerByUserId(userCurrentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId());
            if (roomUserBindDOs != null && roomUserBindDOs.size() > 0) {
                for (RoomUserBindDO roomUserBindDO : roomUserBindDOs) {
                    if (JifenyuanRoomUserTypeEnum.PARTNER.getStatus().equals(roomUserBindDO.getType())) {
                        roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus());
                        //将用户再房间内下线
                        roomUserBindMapper.updateById(roomUserBindDO);
                        notifyPartner(userCurrentRoomDO.getRoomId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
                        notifyObserver(userCurrentRoomDO.getRoomId(), null, null, null, JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);

                        //通知小程序端的还在房间的强制下线
                        ArrayList<Long> longs = CollectionUtil.toList(SecurityFrameworkUtils.getLoginUserId());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("type", JifenyuanRoomEventTypeEnum.MUST_LEAVE_ROOM.getStatus());
                        jsonObject.set("roomId", userCurrentRoomDO.getRoomId());
                        notifyService.notify(longs, jsonObject.toString());


                    } else if (JifenyuanRoomUserTypeEnum.OBSERVER.getStatus().equals(roomUserBindDO.getType())) {
                        roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus());
                        //将观察用户再房间内下线
                        roomUserBindMapper.updateById(roomUserBindDO);
                        //通知观看员下线
                        ArrayList<String> cids = CollectionUtil.toList(roomUserBindDO.getCid());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("type", JifenyuanRoomEventTypeEnum.MUST_LEAVE_ROOM.getStatus());
                        jsonObject.set("roomId", userCurrentRoomDO.getRoomId());
                        if (StringUtils.equals(JifenyuanObserverSourceEnum.mp.getStatus(), roomUserBindDO.getObserverSource())) {
                            notifyService.notifyCids(cids, jsonObject.toString());
                        } else {
                            notifyService.notifyWebCids(cids, jsonObject.toString());
                        }

                    }
                }

            } else {
                //没有绑定关系
            }

            //删除掉用户当前绑定房间
            currentRoomMapper.deleteById(userCurrentRoomDO);

            //判断当前房间是否还有参与人，没有人的话直接将房间置为关闭
            Long aLong = roomUserBindMapper.selectRoomOnlinePartneCount(userCurrentRoomDO.getRoomId());
            if (Objects.isNull(aLong) || aLong.equals(0L)) {
                RoomDO roomDO = new RoomDO();
                roomDO.setStatus(JifenyuanRoomStatusEnum.DISABLE.getStatus());
                roomMapper.update(roomDO, new LambdaUpdateWrapper<RoomDO>().eq(RoomDO::getId, userCurrentRoomDO.getRoomId()));

                List<RoomUserBindDO> roomUserBindDOS = roomUserBindMapper.selectRoomOnlineObserverList(roomDO.getId());
                if (roomUserBindDOS != null && roomUserBindDOS.size() > 0) {
                    List<String> webcids = new ArrayList<>();
                    List<String> mpcids = new ArrayList<>();
                    for (RoomUserBindDO roomUserBindDO : roomUserBindDOS) {
                        if (StringUtils.equals(JifenyuanObserverSourceEnum.mp.getStatus(), roomUserBindDO.getObserverSource())) {
                            mpcids.add(roomUserBindDO.getCid());
                        } else {
                            webcids.add(roomUserBindDO.getCid());
                        }
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.set("type", JifenyuanRoomEventTypeEnum.ROOM_CLOSE.getStatus());
                    jsonObject.set("roomId", userCurrentRoomDO.getRoomId());
//                    发送通知
                    if (mpcids.size() > 0) {
                        notifyService.notifyCids(mpcids, jsonObject.toString());
                    }
                    if (webcids.size() > 0) {
                        notifyService.notifyWebCids(webcids, jsonObject.toString());
                    }
                }
            }

        }


//        UserCurrentRoomDO userCurrentRoomDO = currentRoomMapper.selectOne(UserCurrentRoomDO::getUserId, SecurityFrameworkUtils.getLoginUserId());
//        if (!Objects.isNull(userCurrentRoomDO)) {
//            RoomUserBindDO roomUserBindDO = roomUserBindMapper.selectRoomPartnerByUserId(userCurrentRoomDO.getRoomId(), SecurityFrameworkUtils.getLoginUserId());
//            if(!Objects.isNull(roomUserBindDO)){
//                roomUserBindDO.setStatus(JifenyuanRoomUserStatusEnum.OFFLINE.getStatus());
//                //将用户再房间内下线
//                roomUserBindMapper.updateById(roomUserBindDO);
//                //删除掉用户当前绑定房间
//                currentRoomMapper.deleteById(userCurrentRoomDO);
//                //判断当前房间是否还有参与人，没有人的话直接将房间置为关闭
//                Long aLong = roomUserBindMapper.selectCount(new LambdaQueryWrapper<RoomUserBindDO>()
//                        .eq(RoomUserBindDO::getRoomId, userCurrentRoomDO.getRoomId())
//                        .eq(RoomUserBindDO::getStatus, JifenyuanRoomUserStatusEnum.ONLINE.getStatus())
//                        .eq(RoomUserBindDO::getType, JifenyuanRoomUserTypeEnum.PARTNER.getStatus()));
//                if (Objects.isNull(aLong) || aLong.equals(0L)) {
//                    RoomDO roomDO = new RoomDO();
//                    roomDO.setStatus(JifenyuanRoomStatusEnum.DISABLE.getStatus());
//                    roomMapper.update(roomDO, new LambdaUpdateWrapper<RoomDO>().eq(RoomDO::getId, userCurrentRoomDO.getRoomId()));
//
//                }
//                notifyPartner(userCurrentRoomDO.getRoomId(),null,null,null,JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
//                notifyObserver(userCurrentRoomDO.getRoomId(),null,null,null,JifenyuanRoomEventTypeEnum.MEMBER_CHANGE);
//            }
//
//        }
    }

}
